$(function(){
	var curPage = 1;
    var pageSize = 10;

	var changeTime = function(time) {
		var date = new Date(time);
		var year = date.getFullYear();
		var month = date.getMonth()+1<10?('0'+(date.getMonth()+1)):date.getMonth()+1;
		var day = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
		var min = date.getMinutes() < 10 ? '0'+date.getMinutes():date.getMinutes();

		return year+'-'+month+'-'+day+' '+hour+':'+min;
	}

	var orders = {
		getList: function() {
			$.ajax({
			    url: wsCommon.host + '/api/orders/queryList',
			    dataType: wsCommon.jsonType,
				data: {
                    pageSize: pageSize
                },
			    success: function(res) {
					if(res.code == 1) {
						if(res.result) {
							var pager = res.data.pager;

							orders.initPaging(pager.pages, pager.total, res);
						} else {
							wsCommon.setCookie('go_back_link', window.location.href);
							window.location.href = './passport-login.html';
						}
					}
			    },
			    error: function() {
			        // console.log('接口返回失败');
			    }
			})
		},
		randerList: function(pageData) {
			var tpl = '<thead>\
						<tr>\
							<th>订单号</th>\
							<th>金额</th>\
							<th>下单时间</th>\
							<th>订单状态</th>\
							<th>支付方式</th>\
							<th>操作</th>\
						</tr>\
					</thead>';
			$.each(pageData, function(index, item) {
				var firstTpl = '';
				if(index == 0) {
					firstTpl = 'first';
				}
				var payStatusTpl = '';
				if(item.paymentType != 2 && item.paymentType != 1 && item.status != 'dead' && item.status != 'finish' && item.payStatus != 1) {
					payStatusTpl = '<a href="javascript:;" class="btn btn-import" data-role="tocart3" data-orderid="'+item.orderId+'"><span><span>去付款</span></span></a>';
				}
				var changePayTpl = '';
				if(item.status != 'dead' && item.status != 'finish' && item.payStatus != 1) {
					changePayTpl = '<a href="javascript:;" class="btn btn-simple" data-role="tocart3" data-orderid="'+item.orderId+'"><span><span>修改支付方式</span></span></a>';
				}
				var orderStatusTpl = '';
				if(item.status == 'active') {
					if(item.payStatus == 0) {
						orderStatusTpl = '未支付';
					} else if(item.payStatus == 1) {
						orderStatusTpl = '已支付';
					} else if(item.payStatus == 2) {
						orderStatusTpl = '已付款至到担保方';
					} else if(item.payStatus == 3) {
						orderStatusTpl = '部分付款';
					} else if(item.payStatus == 4) {
						orderStatusTpl = '部分退款';
					} else if(item.payStatus == 5) {
						orderStatusTpl = '全额退款';
					}

				} else if(item.status == 'dead') {
					orderStatusTpl = '已作废';
				} else if(item.status == 'finish') {
					orderStatusTpl = '已完成';
				}
				if(item.shipStatus == 1) {
					orderStatusTpl+= '(已发货)'
				}
				tpl += '<tbody class="'+firstTpl+'"><tr>\
									<td class="order" width="28%"><a href="./member-orderdetail.html?orderId='+item.orderId+'">'+item.orderId+'</a><span class="handle action-view-goods">['+item.itemsList.length+'商品]<i class="icon" data-toggle="7">6</i></span></td>\
									<td class="price">¥'+item.finalAmount+'</td>\
									<td class="datetime">'+changeTime(item.createTime)+'</td>\
									<td class="status">'+orderStatusTpl+'</td>\
									<td class="payments">'+item.paymentName+'</td>\
									<td class="actions" valign="top" rowspan="2">'+payStatusTpl+'<i class="separator"></i>\
									   <a href="./member-orderdetail.html?orderId='+item.orderId+'">查看订单</a>\
									   <i class="separator"></i>\
									   <a href="javascript:;" data-role="buyagain" >再次购买</a>\
									   <i class="separator"></i>'+changePayTpl+'</td>\
								</tr>';
				tpl += '<tr class="goods-row">\
								<td colspan="5">\
									<ul class="member-piclist">';
				$.each(item.itemsList, function(indexDir, itemDir) {
					tpl += '<li class="goods-item" data-goodsid="'+itemDir.goodsId+'" data-productid="'+itemDir.productId+'" data-quantity="'+itemDir.nums+'">\
							   <div class="goods-pic" data-tips="'+itemDir.name+'">\
								   <a href="./info.html?goodsId='+itemDir.goodsId+'&catId='+itemDir.catId+'"><img src="'+itemDir.imageUrl+'" alt="'+itemDir.name+'"></a>\
							   </div>\
							</li>';
				})
				tpl += '</ul>\
						</td>\
					</tr>\
				</tbody>';

			})

			$('[data-role="result"]').html(tpl);
		},
		getPageDates: function() {
            var self = this;

            $.ajax({
                url: wsCommon.host + '/api/orders/queryList',
                dataType: wsCommon.jsonType,
                data: {
					pageNum: curPage,
					pageSize: pageSize
				},
                success: function(res) {

                    // 同步页码
                    var totalPage = res.data.pager.pages;

                    var pageData = res.data.pager.list;
                    var pager = res.data.pager;
                    self.randerList(pageData);
                },
                error: function() {
                    // console.log('分页接口失败');
                }
            });
        },
		initPaging: function(totalPage, totalDataNum, res) {
            var self = this,
                ele = $('[data-role="dirPaging"]');
                if(totalDataNum > 0) {
                    ele.show();
                    var pagination = ele.pagination(totalDataNum, {
                        num_edge_entries: 1,
                        num_display_entries: 4,
                        callback: function(page_index) {
                            if(page_index == 0) {
                                var totalPage = res.data.pager.pages;

                                var pageData = res.data.pager.list;
                                var pager = res.data.pager;
                                orders.randerList(pageData);
                            } else {
                                curPage = page_index + 1;
                                orders.getPageDates();
                            }
                        },
                        items_per_page: pageSize,
                        prev_text: "&lt;&lt;上一页",
                        next_text: "下一页&gt;&gt;",
                        link_to: "javascript:;"
                    });

                }else {
                    ele.hide();
                    $('.member-mod-content').append('<p style="text-align: center;line-height: 100px;font-size: 18px;">没有数据</p>')
                }
        },
		toPay: function() {
			$(document).on('click', '[data-role="tocart3"]', function() {
				var orderInfo = {
					orderId: $(this).attr('data-orderid')
				};

				wsCommon.setCookie('orderInfo', JSON.stringify(orderInfo));

				window.location.href = './cart3.html';
			})
		},
		buyAgain: function() {
			$(document).on('click', '[data-role="buyagain"]', function() {
				var goodsitem = $(this).closest('tr').next('tr').find('.goods-item');
				var arr = [];
				iosOverlay({
					text: "正在跳转页面!",
					duration: 150000
				});

				$.each(goodsitem, function(index, item) {
					var obj = {};
					obj.goodsId = $(item).attr('data-goodsid');
					obj.productId = $(item).attr('data-productid');
					obj.quantity = $(item).attr('data-quantity');
					obj.objType = 'goods';
					arr.push(obj);
				})

				$.ajax({
	                url: wsCommon.host + '/api/cart/addGoodsBatch',
	                dataType: wsCommon.jsonType,
					data: {
						cartGoodsInfo: JSON.stringify(arr)
					},
	                success: function(res) {
						if (res.code == 1) {
							window.location.href = './cart1.html';
						}
					},
					error: function() {

					}
				})
			})
		},
		init: function() {
			this.getList();
			this.toPay();
			this.buyAgain();
		}
	}

	orders.init();
})
